import React, { PureComponent } from 'react';
import { Button, Table, Icon, notification, Modal } from 'antd';
import StructureTree from "../../components/forms/structureTree"
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import moment from "moment"
import "../structureLibrary/index.less"
import "../../Common.less"
class CrossSectionList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedKeys: [],
      data: [],
      total: 0,
      pagination: {
        pageSize: 10,
        pageNum: 1,
        isAsc: "desc",
        orderByColumn: "createTime"
    },
      tloading:false
    }
    this.onSelectChange = this.onSelectChange.bind(this)
    this.onSelect = this.onSelect.bind(this)
    this.getData = this.getData.bind(this)
    this.editComponent = this.editComponent.bind(this)
    this.addStructure = this.addStructure.bind(this)
    this.definitionDelete = this.definitionDelete.bind(this)
    this.paginationChange=this.paginationChange.bind(this)
  }
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };
  onSelect(keys, e) {
    let { id, title } = e.node.props.dataRef;
    const isLeaf = e.node.isLeaf()
    if (isLeaf) {
      this.setState({
        crossSectionCategoryId: id,
        definitionTreeName: title
      })
    }else{
      this.setState({
        crossSectionCategoryId: null,
        definitionTreeName: null
      })
    }
    this.setState({
      selectedKeys: keys,
      selectedRowKeys: []
    })
    this.getData({
      crossSectionCategoryId: id
    })

  }
  async getData(extra = {}) {
    this.setState({
      tloading:true
    })
    const {treeData,pagination}=this.state;
    let res = await this.props.getTemplateList({ ...pagination, ...extra })
    const len=res.rows?res.rows.length:0;
    if(len){
      for (let i = 0; i <len; i++) {
        const item = res.rows[i];
        const node=await worker.getTreeNode(treeData,item.crossSectionCategoryId)
        item.cateName=node.name
      }
    }
    this.setState({
      data: res.rows,
      total:res.total,
      tloading:false
    })
  }
  async paginationChange(pagination2, filters, sorter, extra) {
    const {pagination}=this.state
    await this.setState({
        pagination: {
            orderByColumn:sorter.field||pagination.orderByColumn,
            pageNum: pagination2.current,
            pageSize:5,
            isAsc: sorter.order == "descend" ? "asc" : "desc"
        }
    })
    this.getData()
}
  async componentDidMount() {
    const {dictlist}=this.props;
    let res = await this.props.crossSectionTree()
    let resc = await worker.loopTreeNode(res,null,true,true)
    if (resc) {
      this.setState({
        expandedKeys: resc.map(item => item.key),
        treeData: resc
      })
    }
    this.setState({
      isShowList: dictlist.filter(item => item.dictType == "is_show"),
      isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
      isRequiredList: dictlist.filter(item => item.dictType == "is_required"),
      propertyTypeList: dictlist.filter(item => item.dictType == "property_type"),
      unitList: dictlist.filter(item => item.dictType == "unit"),
      isCalculateList: dictlist.filter(item => item.dictType == "is_calculate"),
      blocklist: dictlist.filter(item => item.dictType == "dynamic_block"),
      definitionFileCategoryList:dictlist.filter(item => item.dictType == "definition_file_category"),
  })
    this.getData()
  }
  editComponent(e, item,type) {
    e.preventDefault();
    this.props.history.push({
      pathname:`/crossSectionDetail/${type=='1'?'overview':'edit'}/${item.id}/-1`
    })
  }
  definitionDelete(e,id) {
    e.preventDefault()
    const {selectedRowKeys}=this.state;
    Modal.confirm({
      title:"提示",
      content:"是否删除选中截面库?",
      cancelText:"取消",
      okText:"确定",
      onOk:()=>{
        this.props.deletecCrossSectionTemplate({ids:id?[id]:selectedRowKeys},res=>{
          this.getData()
        },err=>{
          
        })
      },
      onCancel(){

      }
    })
  }
  addStructure(e) {
    const {crossSectionCategoryId}=this.state;
    e.preventDefault();
    this.props.history.push({
      pathname: `/crossSectionDetail/add/-1/${crossSectionCategoryId||-1}`,
    })
  }
  render() {
    const { pagination,total,selectedRowKeys, selectedKeys, treeData, expandedKeys, data ,tloading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      
      {
        title: '截面库名称',
        dataIndex: 'name',
        key: 'name',
      },
     
      {
        title: '截面库类别',
        dataIndex: 'cateName',
        key: 'cateName',
        width:"100px",
      },
      {
        title: '作者',
        dataIndex: 'createUser',
        key: 'createUser',
        width:"80px"
      },
      {
        title: '截面库描述',
        dataIndex: 'description',
        key: 'description',
      },
     
     
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        ellipsis: true,
        render:text=>moment(text).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        ellipsis: true,
        render:text=>moment(text).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: '操作',
        key: 'action',
        dataIndex: 'action',
        width: "200px",
        render: (text, record) => (
          <span className="operate"><a onClick={(e) => this.editComponent(e, record,1)}><Icon type="retweet" /><span>查看</span></a> <a onClick={(e) => this.editComponent(e, record,2)}><Icon type="edit" /><span>编辑</span></a> <a onClick={(e) => this.definitionDelete(e, record.id)}><Icon type="delete" /><span>删除</span></a></span>
        ),
      },
    ];
    return (
      <div className="libary absMiddle">
        <div className="libaryNav absMiddle">
          <div className="absMiddle navLeft">
            <div className="logo"><Icon type="global" /></div>
            <div className="title">智能设计截面库管理平台</div>
          </div>
          <div className="absMiddle navRight">
            <div>admin</div>
          </div>
        </div>
        <div className="libaryContent absMiddle">
          <div className="libaryTreeBox ">
            <StructureTree selectedKeys={selectedKeys} treeData={treeData} expandedKeys={expandedKeys} onSelect={this.onSelect} onLoaded={(context) => {
              this.setState({
                structureTreeContext: context
              })
            }}></StructureTree>
          </div>
          <div className="tableMain absMiddle">
            <div className="title absMiddle">
              <div>数据列表</div>
              <div className="btnBox"><Button onClick={this.definitionDelete} disabled={!selectedRowKeys.length}>批量删除</Button><Button onClick={this.addStructure} type="primary">添加</Button></div>
            </div>
            <div className="absMiddle tableBox">
              <Table loading={tloading} onChange={this.paginationChange} pagination={{ 'current': pagination.pageNum, pageSize: pagination.pageSize, total }} bordered rowKey={record => record.id} scroll={{ y: 560 }} rowSelection={rowSelection} columns={columns} dataSource={data} />
            </div>
          </div>
        </div>
      </div>
    )
  }
}
export default connect(
  ({
    dict: { dictlist }
  }) => ({
    dictlist
  })
  , dispatch => ({
    crossSectionTree: (values) => dispatch({
      type: 'crossSection/crossSectionTree',
      payload: values
    }),
    getTemplateList: (values) => dispatch({
      type: 'crossSection/getTemplateList',
      payload: values
    }),
    deletecCrossSectionTemplate: (values, onSuccess, onError) => dispatch({
      type: 'crossSection/deletecCrossSectionTemplate',
      payload: {
        values,
        onSuccess,
        onError
      }
    }),
  }))(CrossSectionList);